import {deleteOfStrings, downloadFile, getServiceParams, hooksSet, isNotBlank} from "@/assets/utils/utils";
import {Button, message, Upload as AntdUpload} from "antd";
import {UploadOutlined} from "@ant-design/icons";
import React, {useEffect, useState} from "react";
import {UploadProps} from "@/assets/components/uploadProps";
import {useRequest} from "@@/plugin-request/request";
import {listByIds} from "@/pages/sys/AnnexList/service";

/**
 * 上传组件
 * @param props
 * @constructor
 */
const Upload = (props: UploadProps) => {

  let hide: any;
  const uploadSuccessCallback = props.uploadSuccessCallback;
  const name = props.name || "annexIds";
  const buttonType = props.buttonType || "default";
  // const loadingAutoClose = props.loadingAutoClose || true;
  /**
   * 原文件列表
   */
  const [fileList, setFileList] = useState<any>([])
  /**
   * 获取原附件
   */
  const getOldAnnexesRun = useRequest((ids: string) => listByIds(ids), {
    manual: true,
    onSuccess: (result, params) => {
      let fileList: any = [];
      result.forEach((annex: any) => {
        fileList.push({
          uid: annex.id,
          name: annex.name,
          url: annex.url,
        })
      })
      hooksSet(setFileList, fileList)
    }
  }).run

  /**
   * 启动加载
   */
  useEffect(() => {
    if (props.initIds) {
      getOldAnnexesRun(props.initIds)
    }
  }, [props.initIds]);

  return (
    <AntdUpload
      showUploadList={props.showUploadList == undefined ? true : props.showUploadList}
      multiple={true}
      action={getServiceParams().uploadUrl}
      // @ts-ignore
      beforeUpload={async (file) => new Promise((resolve, reject) => {
        if (file.size / 1024 / 1024 <= 100) {
          hide = hide || message.loading('正在上传')
          return resolve(file);
        } else {
          message.error("文件大小不能超过100MB");
          return reject(file);
        }
      })}
      onChange={({file, fileList}) => {
        if (file.status === "done") {
          let annex = file.response.data
          if (uploadSuccessCallback) {
            uploadSuccessCallback({file, fileList}, annex)
          } else {
            let oldAnnexIds: string = props.form?.getFieldValue(name)
            let newAnnexIds: string = (isNotBlank(oldAnnexIds) ? oldAnnexIds + "," : "") + annex.id
            props.form?.setFieldsValue({[name]: newAnnexIds})
          }
          hide && hide();
        }
        // 把url添加到外层
        fileList.forEach((file)=>{
          if(file.response && file.response.data){
            file.url = file.response.data.url
          }
        })
        hooksSet(setFileList, fileList)
      }}
      fileList={fileList}
      onPreview={(file) => {
        downloadFile(file.response?.data.id || file.uid, file.name)
      }}
      onRemove={(file)=>{
          props.form?.setFieldsValue({[name]: deleteOfStrings(file.response.data.id, props.form.getFieldValue([name]))})
      }}
    >
      <Button type={buttonType} icon={<UploadOutlined/>}>上传附件</Button>
    </AntdUpload>
  )
}

export default Upload;
